//定义电影导演相关接口
const express = require("express");
const router = express.Router();
//引入mysql连接池
const pool = require("../utils/db");
//引入joi表单验证模块
const Joi = require("joi");
//引入响应对象模块
const Response = require("../utils/Response");
//模糊查询
//接口地址/movie-director/name
router.post("/movie-director/name", (req, resp) => {
  let { name } = req.body;
  //表单验证
  let schema = Joi.object({
    name: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  let sql = "select * from movie_director where director_name like ?";

  pool.query(sql, [`%${name}%`], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok(result));
  });
});

//删除导演接口
//接口地址/movie-director/del
router.post("/movie-director/del", (req, resp) => {
  let { id } = req.body;
  //表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //执行删除业务
  let sql = "delete from movie_director where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});
//添加导演接口
//接口地址/movie-director/add
router.post("/movie-director/add", (req, resp) => {
  let { directorName, directorAvatar } = req.body;
  //表单验证
  let schema = Joi.object({
    directorName: Joi.string().required(),
    directorAvatar: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //表单验证通过，执行添加操作
  let sql =
    "insert into movie_director (director_name,director_avatar) values (?,?)";
  pool.query(sql, [directorName, directorAvatar], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok());
  });
});
// 获取所有导演列表;
router.get("/movie-directors", (req, resp) => {
  //获取请求参数 get请求的参数分装在req.query中

  let { page, pagesize } = req.query;
  //需要对服务端传入的值进行验证（服务端表单验证）(joi模块)
  //查询数据库
  let schema = Joi.object({
    page: Joi.number().required(), //page必须是数字，必填
    pagesize: Joi.number().integer().max(100).required(), //pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  let startIndex = (page - 1) * 10;
  let size = parseInt(pagesize);
  let sql = "select * from movie_director limit ?,?";
  pool.query(sql, [startIndex, size], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw err;
    }
    resp.send(Response.ok(result));
  });
});

//将Router接口导出
module.exports = router;
